﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace AppMachine.Controls.Primitive {
    public static class Extend {

        /// <summary>
        /// 通过VisualTreeHelper递归查找指定类型的控件
        /// </summary>
        /// <typeparam name="T">控件类型</typeparam>
        /// <param name="dependencyObject">顶层控件起点</param>
        /// <returns>查找到的指定类型的控件集合</returns>
        public static List<T> GetOfType<T>(this DependencyObject dependencyObject) where T : UIElement {
            List<T> retList = [];

            if (dependencyObject is Popup tempPopup) {
                return tempPopup.Child?.GetOfType<T>();
            }

            if (dependencyObject is T tempTarget) {
                retList.Add(tempTarget);
                return retList;
            }

            int tempCount = VisualTreeHelper.GetChildrenCount(dependencyObject);
            for (int i = 0; i < tempCount; i++) {
                if (VisualTreeHelper.GetChild(dependencyObject, i) is DependencyObject tempDO) {
                    retList.AddRange(tempDO.GetOfType<T>());
                }
            }

            return retList;
        }

    }
}
